package com.simple.system.util;

import com.simple.system.config.JwtConfig;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import jakarta.annotation.PostConstruct;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class CurrentUserUtil {
    private static String SECRET_KEY;

    @Autowired
    private JwtConfig jwtConfig;

    @PostConstruct
    public void init() {
        SECRET_KEY = jwtConfig.getSecretKey();
    }

    public static Long getCurrentUserId(HttpServletRequest request) {
        String authorizationHeader = request.getHeader("Authorization");
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            String token = authorizationHeader.substring(7);
            try {
                Claims claims = Jwts.parser()
                        .setSigningKey(SECRET_KEY)
                        .parseClaimsJws(token)
                        .getBody();
                return Long.parseLong(claims.get("userId").toString());
            } catch (Exception e) {
                // 处理解析异常
                e.printStackTrace();
            }
        }
        return null;
    }
}
